package uthttp

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

func Do(method string, url string, reader io.Reader) (*http.Response, error) {
	req, err := http.NewRequest(method, url, reader)
	if err != nil {
		return nil, err
	}
	return http.DefaultClient.Do(req)
}

func DoString(method string, url string, str string) (*http.Response, error) {
	return Do(method, url, strings.NewReader(str))
}

func DoJson(method string, url string, obj interface{}) (*http.Response, error) {
	jsons, err := json.Marshal(obj)
	if err != nil {
		return nil, err
	}
	return DoString(method, url, string(jsons))
}

func PostJson(url string, data interface{}, rsp interface{}) error {
	client := &http.Client{Timeout: 5 * time.Second}
	jsonStr, err := json.Marshal(data)
	if err != nil {
		return err
	}
	resp, err := client.Post(url, "application/json", bytes.NewBuffer(jsonStr))
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	result, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(string(result))

	err = json.Unmarshal(result, &rsp)
	return err
}
